package com.gensdai.leliang.utils;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class Download {

	final String TAG = "Download";
	DownloadManager downloadManager;
	static long id;
	public static boolean mNewShowInstall = true;
	public static boolean mNewThread = true;
	Context mContext;
	// DownloadChangeObserver changeObserver;
	public Uri CONTENT_URI = null;



	/**
	 * show来判断是否显示通知栏，有进度条数据回调，默认目录
	 * @param URI
	 * @param PackageName（通知栏 应用名）
	 * @param context
	 * @param show  (是否显示状态栏)
	 * @param handler  (是否显示进度条)
	 * @param MSG_DWPACKSIZE
	 */
	public void StartDownload(String URI, String PackageName, Context context,
			boolean show, final Handler handler, final int MSG_DWPACKSIZE) {
		
		if (mNewThread) {
			this.mContext = context;
			this.CONTENT_URI = Uri.parse(URI);
        mStartDown(PackageName, context, show);
		ShowProgressBar(handler, MSG_DWPACKSIZE, id);
		}else {

			Toast.makeText(context, "���������صĶ���Ŷ�����Ե�", Toast.LENGTH_SHORT).show();
		}
	}

	// show来判断是否显示通知栏，有进度条数据回调，自定义目录
	public void StartDownload(String URI, String PackageName, Context context,
			boolean show, final Handler handler, final int MSG_DWPACKSIZE,
			File file) {
		
		if (mNewThread) {
			this.mContext = context;
			this.CONTENT_URI = Uri.parse(URI);
			mStartDownload(PackageName, context, show,file);
			ShowProgressBar(handler, MSG_DWPACKSIZE, id);
		} else {

			Toast.makeText(context, "���������صĶ���Ŷ�����Ե�", Toast.LENGTH_SHORT).show();
		}
	}

	// show来判断是否显示通知栏，无有进度条数据回调，默认目录
	public void StartDownload(String URI,String PackageName ,Context context,
							  boolean show) {
		
		if (mNewThread) {
			this.mContext = context;
			this.CONTENT_URI = Uri.parse(URI);
			mStartDown(PackageName, context, show);
		} else {

			Toast.makeText(context, "���������صĶ���Ŷ�����Ե�", Toast.LENGTH_SHORT).show();
		}
	}

	// show来判断是否显示通知栏，无有进度条数据回调，自定义路径目录
	public void StartDownload(String URI, String PackageName, Context context,
			boolean show, File file) {
		
		if (mNewThread) {
			this.mContext = context;
			this.CONTENT_URI = Uri.parse(URI);
			mStartDownload(PackageName, context, show,file);
		} else {

			Toast.makeText(context, "���������صĶ���Ŷ�����Ե�", Toast.LENGTH_SHORT).show();
		}
	}

	private void queryTaskByIdandUpdateView(final long ID,
											final Handler handler, final int MSG_DWPACKSIZE,
											ScheduledExecutorService ses) {
		DownloadManager.Query query = new DownloadManager.Query();
		query.setFilterById(ID);
		Cursor cursor = downloadManager.query(query);
		String downsize = "0";
		String sizeTotal = "0";
		Log.d(TAG, "if 前面 ");
		if (cursor != null) {
			if (cursor.moveToNext()) {
				Log.d(TAG, "if 里面 ");
				downsize = cursor
						.getString(cursor
								.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
				sizeTotal = cursor
						.getString(cursor
								.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
			}
			Log.i(TAG, "下载量：" + downsize + "总量:" + sizeTotal);

			cursor.close();
		}
		// 判断是否下载完毕，下载完毕则暂停
		if (!downsize.equals(sizeTotal)) {
			if (!"-1".equals(sizeTotal)) {
				String[] string = new String[2];
				string[0] = downsize;
				string[1] = sizeTotal;
				Message msg = new Message();
				msg.what = MSG_DWPACKSIZE;
				msg.obj = string;
				handler.sendMessage(msg);
			}
		} else {
			try {
				mNewThread = true;
				ses.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void ShowProgressBar(final Handler handler,
								 final int MSG_DWPACKSIZE, final long ID) {
		// final Cursor c = null;

		final ScheduledExecutorService ses = Executors
				.newSingleThreadScheduledExecutor();
		ses.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d(TAG, "run 里面 ");
				queryTaskByIdandUpdateView(ID, handler, MSG_DWPACKSIZE, ses);

			}
		}, 0, 2, TimeUnit.SECONDS);

	}

	// 删除正在下载的文件
	public void delDownloads(Context context, String PackName) {

		SharedPreferences sPreferences = context.getSharedPreferences(
				"downloadplato", 0);

		long refernece = sPreferences.getLong(id + "", 0);
		Log.i(TAG, refernece + "");
		if (id == refernece) {
			Toast.makeText(mContext, "删除下载文件", Toast.LENGTH_LONG).show();
			sPreferences.edit().putLong("plato", -1).commit();
			downloadManager.remove(id);
			mNewShowInstall = false;
		} else {
			Toast.makeText(context, "下载文件ID不一致", Toast.LENGTH_LONG).show();
		}
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (mNewShowInstall) {
				long myDwonloadID = intent.getLongExtra(
						DownloadManager.EXTRA_DOWNLOAD_ID, -1);

				SharedPreferences sPreferences = context.getSharedPreferences(
						"downloadplato", 0);

				long refernece = sPreferences.getLong(myDwonloadID + "", 0);
				Log.d(TAG, "refernece" + refernece + "myDwonloadID"
						+ myDwonloadID);
				if (refernece == myDwonloadID) {
					Log.d(TAG, "if (refernece == myDwonloadID) { 里面 ");
					String serviceString = Context.DOWNLOAD_SERVICE;

					DownloadManager dManager = (DownloadManager) context
							.getSystemService(serviceString);

					Intent install = new Intent(Intent.ACTION_VIEW);

					Uri downloadFileUri = dManager
							.getUriForDownloadedFile(myDwonloadID);

					install.setDataAndType(downloadFileUri,
							"application/vnd.android.package-archive");

					install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(install);
					mNewShowInstall = true;
				}
			}
		}
	};

	public void mLogout(){
		mContext.unregisterReceiver(broadcastReceiver);
	}

	private void mStartDown(String PackageName, Context context,
							boolean show){
		downloadManager = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);// 获取下载服务

		DownloadManager.Request request = new DownloadManager.Request(
				CONTENT_URI);// //创建下载请求
		// 设置网络环境
		request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
				| DownloadManager.Request.NETWORK_WIFI);// //设置允许使用的网络类型，这里是移动网络和wifi都可以

		// 设置通知栏内标题显示内容
		if (show) {
			request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);// 设置状态可见
			request.setTitle("下载");// 设置状态显示内容，正在下载
			request.setDescription(PackageName + "正在下载");// 设置什么东西在下载
			request.setAllowedOverRoaming(false);
		} else {
			request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);// 设置状态隐藏
		}
		request.setAllowedOverRoaming(false);// 是否允许漫游？
		// 设置为可被媒体扫描器找到
		request.allowScanningByMediaScanner();
		// 设置为可见和可管理
		request.setVisibleInDownloadsUi(true);
		// 设置存放目录 //(获取当前上下文，类型，路径)
		File file = new File("data/data/" + PackageName + id);
		Log.i(TAG, "存放的目录：" + file);
		String s = file.getPath();
		request.setDestinationInExternalFilesDir(context, s, "download.apk");// Environment.DIRECTORY_DOWNLOADS
		Log.i(TAG, "存放的目录：" + s);
		// 获取下载ID

		id = downloadManager.enqueue(request);// 开始放入下载序列，返回唯一ID
		mNewThread = false;

		// 保存ID
		SharedPreferences sPreferences = context.getSharedPreferences(
				"downloadplato", 0);
		sPreferences.edit().putLong(id + "", id).commit();

		mNewShowInstall = true;
		mContext.registerReceiver(broadcastReceiver, new IntentFilter(
				DownloadManager.ACTION_DOWNLOAD_COMPLETE));// 注册广播
	}



	private void mStartDownload(String PackageName, Context context,
								boolean show,File file){
		downloadManager = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);// 获取下载服务

		DownloadManager.Request request = new DownloadManager.Request(
				CONTENT_URI);// //创建下载请求
		// 设置网络环境
		request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
				| DownloadManager.Request.NETWORK_WIFI);// //设置允许使用的网络类型，这里是移动网络和wifi都可以

		// 设置通知栏内标题显示内容
		if (show) {
			request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);// 设置状态可见
			request.setTitle("下载");// 设置状态显示内容，正在下载
			request.setDescription(PackageName + "正在下载");// 设置什么东西在下载
			request.setAllowedOverRoaming(false);
		} else {
			request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);// 设置状态隐藏
		}
		request.setAllowedOverRoaming(false);// 是否允许漫游？
		// 设置为可被媒体扫描器找到
		request.allowScanningByMediaScanner();
		// 设置为可见和可管理
		request.setVisibleInDownloadsUi(true);
		// 设置存放目录 //(获取当前上下文，类型，路径)
//		File file = new File("data/data/" + PackageName + id);
		Log.i(TAG, "存放的目录：" + file);
		String s = file.getPath();
		request.setDestinationInExternalFilesDir(context, s, "download.apk");// Environment.DIRECTORY_DOWNLOADS
		Log.i(TAG, "存放的目录：" + s);
		// 获取下载ID

		id = downloadManager.enqueue(request);// 开始放入下载序列，返回唯一ID
		mNewThread = false;

		// 保存ID
		SharedPreferences sPreferences = context.getSharedPreferences(
				"downloadplato", 0);
		sPreferences.edit().putLong(id + "", id).commit();

		mNewShowInstall = true;
		mContext.registerReceiver(broadcastReceiver, new IntentFilter(
				DownloadManager.ACTION_DOWNLOAD_COMPLETE));// 注册广播
	}
}
